<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateOrdersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id')->comment('用户id');
            $table->unsignedInteger('agent_user_id')->comment('所属代理id');
            $table->string('order_sn')->comment('订单编号');
            $table->string('device_sn')->comment('设备编号');
            $table->float('order_money')->comment('订单金额');
            $table->float('real_pay_money')->comment('实际支付金额；不含优惠券等特殊支付');
            $table->string('status')->comment('订单状态 wait_pay 待支付；paid 已支付；service 服务中；refund 已退款；success 交易成功');
            $table->timestamp('paid_at')->nullable()->comment('服务开始时间');
            $table->timestamp('service_start_at')->nullable()->comment('服务开始时间');
            $table->timestamp('service_end_at')->nullable()->comment('服务结束时间');
            $table->integer('consume_duration')->default(0)->comment('消费时长 单位：分钟');
            $table->string('port')->comment('消费的设备插口');
            $table->integer('proration')->comment('分红比例 单位： %');
            $table->json('prorations')->comment('各级代理分红比例 {v1:xxx，v2:xxx，v3:xxx} 单位: %');
            $table->json('ladder_price')->comment('设备定价策略 {before_price: xxx, after_price: xxx, boundary_time: xxx}');
            $table->string('source')->nullable()->comment('下单来源');
            $table->string('remark')->nullable()->comment('订单备注');
            $table->timestamps();

            $table->unique('order_sn');
            $table->index('user_id');
            $table->index('agent_user_id');
            $table->index('device_sn');

            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('agent_user_id')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('orders');
    }
}
